<template>
	<div>
		<breadcrumb></breadcrumb>

		<!-- 列表 -->
		<div class="main">
			<div class="main_head">
				<div class="main_head_left">
					<!-- <div class="dialogs">
                        <div style="display: flex;align-items: center;">
                            <div style="width: 200px;">
                                <el-input size="small" placeholder="请输入内容" v-model="keyWord" clearable></el-input>
                            </div>
                            <el-button type="primary" @click="cread" style="margin-left: 15px;">查询</el-button>
                        </div>
                    </div> -->
					<div class="inputItem">
						<div class="title">门店名称(编号)</div>
						<div class="inputBox">
							<el-input v-model="keyWord" @keyup.enter.native="cread(1)" clearable>
							</el-input>
						</div>
					</div>
					<div class="inputItem">
						<div class="title">状态</div>
						<div class="inputBox">
							<el-select v-model="stateValue" placeholder="请选择"><el-option v-for="item in options"
									:key="item.value" :label="item.label" :value="item.value"></el-option></el-select>
						</div>
					</div>
					<div class="inputItem">
						<div class="title">编辑时间</div>
						<el-date-picker size="small" v-model="createTime" type="datetimerange"
							:picker-options="createTime" range-separator="至" start-placeholder="开始日期"
							end-placeholder="结束日期" align="right" value-format="yyyy-MM-dd HH:mm:ss">
						</el-date-picker>
					</div>

					<!-- 查询 -->
					<el-button type="primary" size="small" icon="el-icon-search" @click="cread(1)">查询</el-button>
					<el-button type="plain" size="small" icon="el-icon-refresh-right" @click="CleanUp">清空</el-button>
				</div>
				<div class="main_head_right">
					<button class="addCargoOwner" @click="showAddAddress()">
						<i class="el-icon-plus iconBtn"></i>
						<span>新增</span>
					</button>
					<button class="addCargoOwner" @click="Download">
						下载地址簿模板
					</button>
					<el-button class="addCargoOwner" @click="exportDown" :loading="exportLoading">
						导出地址薄
					</el-button>
					<el-upload ref="upload" action="https://jsonplaceholder.typicode.com/posts/" :before-upload="upload"
						:show-file-list="false" accept=".xlsx,.xls" >
						<el-button class="addCargoOwner">导入地址簿</el-button>
					</el-upload>
					<el-button class="addCargoOwner" @click="clearAddr()">
						一键清空
					</el-button>
				</div>
			</div>

			<div class="list">
				<el-table :data="records" style="width: 100%" header-align="left">
					<el-table-column align="left" prop="SerialNumber" width="70" label="序号">
					</el-table-column>
					<el-table-column align="left" prop="sname" label="门店名称" min-width="220"></el-table-column>
					<el-table-column align="left" prop="storeNo" label="门店编号" width="120">
					</el-table-column>
					<el-table-column align="left" label="坐标" width="180">
						<template slot-scope="scope">
							<div v-if="scope.row.status == 1" style="color: red">
								{{ scope.row.lng + "," + scope.row.lat }}
							</div>
							<div v-else>
								{{ scope.row.lng + "," + scope.row.lat }}
							</div>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="contacts" label="联系人" width="100">
						<template slot-scope="scope">
							<div>{{ scope.row.contacts || "--.--" }}</div>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="phone" label="联系人电话" width="120">
						<template slot-scope="scope">
							<div>{{ scope.row.phone || "--.--" }}</div>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="addr" label="收货地址" min-width="260">
					</el-table-column>
					<el-table-column align="left" prop="updateTime" label="更新时间" width="140">
						<template>
							<div slot-scope="scope">
								<div>{{ scope.row.updateTime || "--.--" }}</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column align="left" prop="updateBy" label="更新人" width="100">
						<template>
							<div slot-scope="scope">
								<div>{{ scope.row.updateBy || "--.--" }}</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column align="left" label="操作" width="120">
						<template slot-scope="scope">
							<div>
								<el-button type="text" size="small" @click="showAlterDialog(scope.row)">编辑</el-button>
								<el-button type="text" size="small" @click="delBtn(scope.row)">删除</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="paginationBox">
				<el-pagination @current-change="changePages($event)" class="pagination" background
					layout="slot,prev, pager, next" :current-page.sync="pageCurrent" :total="data.total * 1"
					:page-size="data.size * 1" :pager-count="5">
					<template slot>
						<span style="
                color: #686868;
                font-size: 12px;
                margin-right: 20px;
                display: inline-block;
              ">
							共{{ data.total }}条,每页{{ data.size }}条
						</span>
					</template>
				</el-pagination>
			</div>

			<el-dialog :title="title" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
				class="dialog" @close="beforeClose">
				<el-form ref="formdata" :model="formdata" :rules="formRules" v-loading="loading" label-width="100px">
					<el-form-item label="门店编号" prop="storeNo">
						<el-input placeholder="请输入内容" onkeyup="value=value.replace(/[^\d]/g,'')"
							v-model="formdata.storeNo" clearable size="small" :disabled="title == '编辑地址'"></el-input>
					</el-form-item>
					<el-form-item label="门店名称" prop="sname">
						<el-input placeholder="请输入内容" v-model="formdata.sname" size="small" clearable></el-input>
					</el-form-item>
					<div style="width: 500px;">
						<el-form-item label="经度,纬度" prop="zuobiao">
							<el-input placeholder="示例：106.322154,29.322154" size="small"
								v-model="formdata.zuobiao"></el-input>
						</el-form-item>
					</div>
					<div>
						<div class="link" @click="jumpBaidu">
							点击前往百度地图确认坐标系
						</div>
					</div>
					<el-form-item label="联系人" prop="contacts">
						<el-input placeholder="请输入内容" size="small" v-model="formdata.contacts" clearable></el-input>
					</el-form-item>
					<el-form-item label="联系人电话" prop="phone">
						<el-input placeholder="请输入内容" size="small" v-model="formdata.phone" clearable></el-input>
					</el-form-item>

					<el-form-item label="收货地址" prop="address">
						<el-input placeholder="请输入内容" v-model="formdata.address" size="small" clearable></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="ByStoreNo">确 定</el-button>
				</span>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	import {
		read,
		utils
	} from "xlsx";
	import {
		workbook2blob,
		openDownloadDialog
	} from '@/common/blobAndOpenDownload.js'
	import XLSX from "xlsx";
	import breadcrumb from "@/components/breadcrumb.vue";
	import httpApi from "@/http";
	// import exportFromJSON from 'export-from-json'

	export default {
		data() {
			let validStoreNo = (rule, value, callback) => {
				let params = {};
				if (this.formdata.supplierId != "") {
					// params = {
					// 	storeNo: value,
					// 	supplierId: this.formdata.supplierId,
					// };
					callback(); // 编辑地址时不验证,因为已经禁用输入框,只要确保回填无误
				} else {
					params = {
						storeNo: value,
					};
					delete params.supplierId;
				}
				////console.log('统一', params);
				httpApi.basicSettingsApi.checkStoreNo(params).then((res) => {
					////console.log('校验', res);
					if (res.data.code == 200) {
						callback(); //通过不传值
					} else if (res.data.code == 202) {
						callback(new Error("门店编号已存在")); //callback()传了参数字段就代表校验不通过
					}
				});
			};
			return {
				stateValue: "",
				options: [{
						value: "",
						label: "全部",
					},
					{
						value: "0",
						label: "正常",
					},
					{
						value: "1",
						label: "异常",
					},
				],
				createTime: [],
				title: "新增地址",
				records: [],
				records1: [],
				data: {
					total: "",
					size: "",
				},
				exportLoading: false,
				formdata: {
					storeNo: "",
					address: "",
					sname: "",
					phone: "",
					contacts: "",
					supplierId: "",
					lng: "",
					lat: "",
					zuobiao: ''
				},
				formRules: {
					storeNo: [{
							required: true,
							message: "不能为空",
							trigger: "blur"
						},
						{
							validator: validStoreNo,
							trigger: "blur"
						},
					],
					address: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
					sname: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
					// phone: [{ required: true, message: "不能为空", trigger: "blur" }],
					// contacts: [{ required: true, message: "不能为空", trigger: "blur" }],
					lng: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
					lat: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
					zuobiao: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
				},
				loading: false,
				pageCurrent: 1,
				pageSize: 15,
				dialogVisible: false,
				keyWord: "",
			};
		},
		methods: {
			//清空地址
			clearAddr(){
				let that=this;
				this.$confirm("此操作将永久删除"+that.data.total+"条门店信息, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(() => {
						that.$http.orderApi
							.storeAddrRemoveAll({
								keyWord: that.keyWord,
								status: that.stateValue,
								startTime: that.createTime != null ? that.createTime[0] : "", //开始时间
								endTime: that.createTime != null ? that.createTime[1] : "", //结束时间
							})
							.then((res) => {
								if (res.data.code == 200) {
									that.$message({
										type: "success",
										message: "删除成功!",
									});
									that.cread();
								}
							});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除",
						});
					});
			},
			//导出文档

			exportDown() {
				this.exportLoading = true
				let cont = JSON.parse(JSON.stringify(this.records1))
				const sheetData1 = cont.map((item, index) => ({
					'序号': index + 1,
					'门店编号': item.storeNo,
					'门店名称': item.sname,
					'经纬度': item.lng + ',' + item.lat,
					'联系人': item.contacts,
					'联系人电话': item.phone,
					'详细地址': item.addr,
				}));
				const sheet1 = XLSX.utils.json_to_sheet(sheetData1);



				for (let key in sheet1) {
					// //console.log(key);
					if (key != '!ref' && key != '!merges' && key != '!cols') {
						sheet1[key].s = {
							alignment: {
								horizontal: "center",
								vertAlign: "center"
							},
						}
					}
				}

				let cols = []; // 设置每列的宽度
				// wpx 字段表示以像素为单位，wch 字段表示以字符为单位
				// //console.log(sheetData1);
				let headCol = ['序号',
					'门店编号',
					'门店名称',
					'经纬度',
					'联系人',
					'联系人电话',
					'详细地址',
				]

				for (let i = 0; i <= headCol.length; i++) {
					let col = {};
					col.wch = this.getCellWidth(headCol[i], sheetData1)
					cols.push(col)
				}
				sheet1['!cols'] = cols; // 设置列宽信息到工作表
				const wb = XLSX.utils.book_new(); // 初始化一个excel文件
				XLSX.utils.book_append_sheet(wb, sheet1, '地址簿数据表');
				const workbookBlob = workbook2blob(wb);


				openDownloadDialog(workbookBlob, `地址簿数据表.xlsx`);
				this.exportLoading = false

			},
			getCellWidth(value, sheetData) { //计算每列的需设置的宽度
				if (value == '序号') {
					return 10
				} else if (value == '门店编号') {
					return 13
				} else if (value == '门店名称') {
					return 42
				} else if (value == '经纬度') {
					return 40
				} else if (value == '联系人') {
					return 12
				} else if (value == '联系人电话') {
					return 18
				} else if (value == '详细地址') {
					let maxWitdh = ''
					sheetData.forEach(item => {
						let chineseLength
						if (item['详细地址'].match(/[\u4e00-\u9fa5]/g) == null) {
							chineseLength = 10
						} else {
							chineseLength = item['详细地址'].match(/[\u4e00-\u9fa5]/g).length;
						}

						let otherLength = item['详细地址'].length - chineseLength;
						let width = chineseLength * 2.1 + otherLength * 1.1
						if (maxWitdh < width) {
							maxWitdh = width
						}
						// //console.log('max', maxWitdh);

					})
					return maxWitdh
				}
			},
			beforeClose() {
				if (this.title == "编辑地址") {
					for (let key in this.formdata) {
						this.formdata[key] = "";
						// //console.log(key);
						this.$refs["formdata"].clearValidate(key);
					}
				}
			},
			clearUp() {
				for (let key in this.formdata) {
					this.formdata[key] = "";
				}
			},
			ByStoreNo() {
				if (this.loading) {
					this.$message.warning("正在提交中");
					return;
				}
				this.loading = true;
				switch (this.title) {
					case "新增地址":
						this.$refs["formdata"].validate((valid) => {
							if (valid) {
								if (this.formdata.zuobiao.indexOf(',') == -1) {
									this.$message.error('请确认坐标是否正确')
									return false
								}
								let cont = this.formdata.zuobiao.split(',')
								this.formdata.lng = cont[0]
								this.formdata.lat = cont[1]
								httpApi.basicSettingsApi
									.getAddStoreAddr(this.formdata)
									.then((res1) => {
										if (res1.data.code == 200) {
											this.$message.success("新增地址成功");
											this.dialogVisible = false;
											this.clearUp(); //清空表单
											this.cread();
										}
									});
							} else {
								this.$message.error("请正确填写完整信息");

								return false;
							}
						});
						this.loading = false;
						break;
					case "编辑地址":
						this.$refs["formdata"].validate((valid) => {
							if (valid) {
								if (this.formdata.zuobiao.indexOf(',') == -1) {
									this.$message.error('请确认坐标是否正确')
									return false
								}
								let cont = this.formdata.zuobiao.split(',')
								this.formdata.lng = cont[0]
								this.formdata.lat = cont[1]

								this.$http.orderApi
									.querymodifyStoreAddrByStoreNo(this.formdata)
									.then((res) => {
										if (res.data.code == 200) {
											this.$message.success("修改成功");
											this.clearUp(); //清空表单
											this.dialogVisible = false;
											this.cread();
										}
									});
							} else {
								this.$message.error("请正确填写完整信息");
								return false;
							}
						});
						this.loading = false;
						break;
				}
			},
			showAddAddress() {
				this.title = "新增地址";
				this.dialogVisible = true;
				this.formdata.supplierId = "";
				//console.log(this.formdata);
			},
			showAlterDialog(e) {
				this.title = "编辑地址";

				for (let k in this.formdata) {
					if (k == "address") {
						this.formdata.address = e.addr;
						continue;
					}
					this.formdata[k] = e[k];
				}
				this.formdata.zuobiao = e.lng + ',' + e.lat
				this.dialogVisible = true;
			},
			jumpBaidu() {
				window.open("https://api.map.baidu.com/lbsapi/getpoint/index.html");
			},
			delBtn(e) {
				let that = this;
				this.$confirm("此操作将永久删除该门店, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(() => {
						that.$http.orderApi
							.removeStoreAddrByStoreNo({
								storeNo: e.storeNo,
								supplierId: e.supplierId,
							})
							.then((res) => {
								if (res.data.code == 200) {
									that.$message({
										type: "success",
										message: "删除成功!",
									});
									that.cread();
								}
							});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消删除",
						});
					});
			},
			Download() {
				const a = document.createElement("a");
				a.href = "/storeAddress.xlsx";
				a.download = "storeAddress.xlsx";
				a.style.display = "none";
				document.body.appendChild(a);
				a.click();
				a.remove();
			},
			changePages(e) {
				this.pageCurrent = e;
				this.cread();
			},
			//批量订单的创建，excle
			//导入excel文档
			upload(file, fileList) {
				let files = {
					0: file,
				};
				this.readExcel1(files);
			},
			// 获取导入excel文档的数据
			readExcel1(files) {
				var that = this;
				if (files.length <= 0) {
					return;
				}
				if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
					this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
					return;
				}
				const fileReader = new FileReader();
				var yind = 0;
				fileReader.onload = (ev) => {
					try {
						const data = ev.target.result;
						const workbook = read(data, {
							type: "binary",
						});
						const wsname = workbook.SheetNames[0];
						const ws = utils.sheet_to_json(workbook.Sheets[wsname]);

						let list = [];
						ws.forEach((item, index) => {
							yind = index + 1;
							
							list.push({
								sname: item["门店名称"],
								storeNo: item["门店编号"],
								address: item["详细地址"],
								phone: item["联系人电话"],
								contacts: item["联系人"],
								//   economize: item["省(直辖市)"],
								//   district: item["区/县"],
								//   city: item["市"],
								coordinate: item["经纬度"]
							});
						});

						this.$http.orderApi.importStoreAddr(list).then((res) => {
							if (res.data.code == 200) {
								this.$message.success("导入成功");
								this.cread();
								// loading.close();
							}
						});
					} catch (e) {
						if (yind == 0) {
							this.$message.error(res.data.msg);
						} else {
							this.$message.error("导入失败,第" + yind + "地址异常");
						}

						return false;
					}
				};
				fileReader.readAsBinaryString(files[0]);
			},
			CleanUp() {
				this.keyWord = "";
				this.createTime = "";
				this.stateValue = "";
				this.cread(1);
			},
			async cread(current) {
				var d = {
					pageIndex: current || this.pageCurrent,
					pageSize: this.pageSize,
					keyWord: this.keyWord,
					status: this.stateValue,
					startTime: this.createTime != null ? this.createTime[0] : "", //开始时间
					endTime: this.createTime != null ? this.createTime[1] : "", //结束时间
				}
				if (this.stateValue != "") {
					d.status = this.stateValue
				}
				let res = await this.$http.orderApi.queryStoreAddrBySupplierId(d);
				this.records = res.data.data.records;
				this.data.size = res.data.data.size;
				this.data.total = res.data.data.total;
				this.records.forEach((item, i) => {
					let num = i + 1 + Number(this.pageSize) * (this.pageCurrent - 1);
					item.SerialNumber = num;
				});
				let res1 = await this.$http.orderApi.exportStoreAddrBySupplierId(d);
				this.records1 = res1.data.data;
			},
		},
		created() {
			this.cread();
		},
		mounted() {},
		components: {
			breadcrumb,
		},
	};
</script>

<style lang="scss" scoped>
	.main {
		width: 100%;

		height: calc(100vh - 127px);
		background-color: #fff;
		padding: 0px 30px 0px 30px;
		// overflow-x: scroll;
		// min-width: 970px;

		.main_head {
			padding: 10px 0;

			.main_head_left {
				font-size: 12px;
				color: #262626;
				display: flex;

				.inputItem {
					display: flex;
					align-items: center;
					margin-right: 23px;

					>.title {
						color: #262626;
						font-size: 12px;
						margin-right: 7px;
					}

					>.inputBox {
						width: 160px;

						.select {
							::v-deep .el-input__icon {
								line-height: 0;
							}
						}

						::v-deep .el-input__inner {
							height: 32px;
							font-size: 12px;
						}

						::v-deep .el-input__inner::placeholder {
							color: #c3c3c3;
							font-size: 12px;
						}
					}
				}
			}

			.main_head_right {
				display: flex;
				justify-content: flex-end;
				margin-top: 10px;

				.addCargoOwner {
					background-color: #1890ff;
					border-radius: 4px;
					height: 32px;
					color: #ffffff;
					font-size: 12px;
					padding: 8px 17px 9px 17px;
					transition: 0.2s;
					cursor: pointer;
					margin-right: 17px;

					.iconBtn {
						margin-right: 7px;
						font-size: 12px;
					}

					&:hover {
						opacity: 0.8;
					}
				}
			}
		}

		.list {
			height: calc(100% - 143px);

			::v-deep .el-table__body-wrapper {
				height: calc(100vh - 320px);
				overflow-y: scroll;
			}

			// 表头样式
			::v-deep .el-table__header th {
				background-color: #f0f6fd;
				color: #262626;
				font-size: 12px;
				font-weight: bold;
				text-align: left;

				// 表 body的td
				::v-deep .el-table__body td {
					color: #595959;
					font-size: 12px;
				}
			}

			.stateBtns {
				height: 30px;

				::v-deep .el-button {
					font-size: 12px;
					border: none;
					width: 76px;
					height: 30px;
					margin: 0 auto;
					box-sizing: border-box;
				}

				.icon-dian {
					font-size: 12px;
				}

				.Pass {
					background-color: #ecf5fe;
					color: #1890ff;
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 10px 10px 9px;
				}

				.noPass {
					background-color: #fde8e9;
					color: #f7555d;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}

		.paginationBox {
			width: 100%;
			background-color: #fff;
			display: flex;
			height: 48px;
			align-items: center;

			.pagination {
				margin-left: auto;
			}
		}
	}

	.dialog {
		.link {
			color: #1890ff;
			cursor: pointer;
			transition: 0.2s;
			margin-bottom: 15px;
			margin-left: 335px;
			display: inline-block;

			&:hover {
				opacity: 0.8;
			}
		}

		// 标题
		::v-deep .el-dialog__header {
			border-bottom: 1px solid #f0f0f0;
			padding: 15px 20px;
			color: #262626;
			font-size: 14px;
			font-weight: bold;
			height: 50px;
		}

		::v-deep .el-dialog__title {
			font-size: 14px;
			color: #303133;
			font-weight: bold;
		}

		//关闭图标
		::v-deep .el-dialog__headerbtn .el-dialog__close {
			font-size: 15px;
		}

		::v-deep .el-dialog__body {
			padding: 25px 40px 24px;
		}

		//   表格
		::v-deep .el-form-item__label {
			line-height: 32px;
			font-size: 12px;
			color: #262626;
			padding-top: 4px;
			width: 100%;
		}

		::v-deep .el-input__inner {
			line-height: 32px;
			height: 32px;
			padding: 0 10px;
		}

		.cancelBtn {
			width: 80px;
			height: 36px;
			border: 1px solid #d9d9d9;
			color: #262626;
			font-size: 12px;
			border-radius: 4px;
			background-color: #fff;
		}

		.submitBtn {
			background-color: #1890ff;
			width: 80px;
			height: 36px;
			color: #fff;
			border-radius: 4px;
			font-size: 12px;
		}

		.inputSelect_left {
			height: 32px;

			::v-deep .el-input__inner {
				border-radius: 4px 0px 0px 4px;
			}
		}

		.inputSelect_right {
			height: 32px;

			::v-deep .el-input__inner {
				border-radius: 0px 4px 4px 0px;
				border-left: none;
				background-color: #f5f7fa;
				font-size: 12px;
				color: #606266;
			}
		}

		::v-deep .el-input__icon {
			line-height: 0;
		}

		::v-deep .el-form-item__content {
			line-height: 0;
		}

		.notes ::v-deep .el-textarea .el-input__count {
			bottom: 15px;
			color: #c0c4cc;
		}
	}
</style>